#define xsize 352 
#define ysize 288
#include <stdio.h>


void print_frame_binary(unsigned short * imm)
{
	FILE * fid2;
	unsigned int i=0;
	//unsigned int binarysize=xsize*(ysize/16);
	fid2 = fopen("pimpBINARY.txt","w");
	for(i=0; i<6336; i++)
	{
		fprintf(fid2, "%u\n", imm[i]);
		//if(i%1000==0){
		//	printf("%i \n",i);
		//}
	}

	fclose(fid2);
	//printf("done printing frame\n");
	exit(1);
	
}

void threshfuncv2(unsigned short *image, unsigned short*imm){ //image[xsize*ysize]){
//	short *imm[xsize*ysize/16];
	unsigned short temp1,temp2;
	short thresh;
	long threshl;
	//short bit;
	short max=0;
	long sum=0;
	long greensum=0;
	long redsum=0;
	short bitcount=0;
	short shortcount=0;
	double r_av,g_av;
	unsigned short shorttemp;
	unsigned long i;
//	unsigned short temp_everything[xsize*ysize];
	unsigned short temp;
	//short stupid_temp;

	for(i=0;i<(50688L);i++){
		//stupid_temp = (*(image+i));
//		cout<<"ANNA BANANA" << endl;

		temp1=(((*(image+i))>>8)&255);		//8 most significant bits		
		temp2=(((*(image+i)))&255);			//8 lower bits

//		cout << "JOSH!!!"<<endl;
        greensum+=(temp1>>2)&7+(temp2>>2)&7;
        redsum+=(temp1>>5)&7+(temp2>>5)&7;
		sum = sum+temp1+temp2;
//		temp_everything[2*i]=temp1;

//		cout << "ESTHER IS PIMP"<<endl;
//		temp_everything[2*i+1]=temp2;

//		cout <<"I LOVE ROBOTS"<<endl;
		if (temp1>max){
			max = temp1;
		}
		else if (temp2>max){
			max = temp2;
		}
	}

	threshl=sum/xsize/ysize;
	thresh=(short)threshl;
	thresh=(thresh+max)/2;

	r_av=(double)(redsum)/xsize/ysize;
	g_av=(double)(greensum)/xsize/ysize;


	for(i=0;i<(101376L);i++){
		//temp=(image[i]&3)*14-((image[i]>>2)&7)*3-((image[i]>>5)&7)*3;
		
		//if (temp_everything[i]>=thresh)
		if((i%2)==0){
			temp=((*(image+(i/2)))>>8)&255;
		}
		else{
			temp=(*(image+((i-1)/2)))&255;
		}
		//if(((((temp_everything[i])>>5)&7)<<r_av)&&((((temp_everything[i])>>2)&7)<<g_av)&&(((temp_everything[i])&3)>0))
		if(((((temp)>>5)&7)<2)&&((((temp)>>2)&7)<5)&&(((temp)&3)>0))
		{
			shorttemp+=1<<(15-bitcount);
		}
	//	cout<<"DO THE ROBOT!!!! DO THE MONKEY!!!" << endl;
		if (bitcount==15){
			bitcount=0;
			imm[shortcount]=shorttemp;
			shortcount++;
			shorttemp=0;
		}
		else{
			bitcount++;
		}
	//	cout <<"NO PROGRAM!!"<<endl;
	}
	//printf("printing binary \n");
	//print_frame_binary(imm);	
}
